//
//  UIImageView+Extension.swift
//  微博Swift
//
//  Created by  justinchou on 16/2/29.
//  Copyright © 2016年  justinchou. All rights reserved.
//

import UIKit

extension UIImageView {
    
    convenience init(justin_imageName: String) {
        self.init()
        
        image = UIImage(named: justin_imageName)
    }
    
    /// 设置图像
    ///
    /// - parameter urlString:       urlString
    /// - parameter placeholderName: 占位图像名
    /// - parameter imageSize:       裁切图像大小，默认 CGSizeZero，不裁切
    /// - parameter isCorner:        是否圆角，默认 false，仅在裁切图像时有效
    /// - parameter backColor:       背景颜色，默认白色，仅在裁切图像时有效
    func justin_setImageWithURL(
        urlString: String?,
        placeholderName: String?,
        imageSize: CGSize? = CGSizeZero,
        cornerRadius: CGFloat? = 0,
        backColor: UIColor? = UIColor.whiteColor()) {
            
            var placeholderImage: UIImage?
            
            if placeholderName != nil {
                placeholderImage = UIImage(named: placeholderName!)
            }
            
            //如果url为nil
            guard let urlString = urlString,
                let url = NSURL(string: urlString) else {
                    // 如果 urlString 为 nil，但是指定了占位图像，显示占位图像
                    image = placeholderImage
                    return
            }
            
            if imageSize == CGSizeZero {
                
                sd_setImageWithURL(url, placeholderImage: placeholderImage)
            } else {
                sd_setImageWithURL(url, placeholderImage: placeholderImage) { (image, _, _, _) -> Void in
                    
                    // 判断图像是否现在成功
                    guard let image = image else {
                        return
                    }
                    
                    image.justin_asyncDrawImage(imageSize, cornerRadius: cornerRadius, backColor: backColor) { (image) -> () in
                        self.image = image
                    }
                    
                }
            }
            
            
    }
    
    
    
    
    
    
    
    
}
